﻿using UnityEngine;

public class PoolItemBase: MonoBehaviour
{
    protected ResService resService;
    protected Item item;//用于回收对象
    protected float time;
    protected bool isReady = false;
    
    public void SetLiftTime(float time)
    {
        this.time = time;
    }
    protected virtual void Awake()
    {
        resService = GameRoot.Instance.resService;
    }

    private void OnEnable()
    {
        if (!isReady) { return; }
        Spawn();
    }

    private void OnDisable()
    {
        if (!isReady) { return; }
        Recycle();
    }
    protected virtual void Recycle()//初始化完成后，每次掩藏调用
    {
        if (this == null || gameObject==null)  { return; }
        resService.RecycleItem(item);
    }

    public virtual void Spawn()//初始化完成后，每次显示调用
    {
        if (time > 0)
        {
            GameRoot.Instance.timerService.AddTimer((int)time * 1000, DisEnable);
        }
    }
    public virtual void Init(Item item)//被对象池创建时调用
    {
        isReady = true;
        this.item = item;
    }
    /// <summary>
    /// 可在需要回收时调用，比直接设置Active更安全
    /// </summary>
    public void DisEnable()
    {
        if (this ==null||gameObject==null)
        {
            return;
        }
        if (transform.parent != resService.PoolRoot)//为了防止，已经回收，但后面被销毁了
        {
            transform.parent = resService.PoolRoot.transform;
        }
        this.gameObject.SetActive(false);
    }
}